package com.edu.controller;

import com.edu.bean.Book;
import com.edu.service.BookService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class BookController {
    @Resource
    private BookService bookService;

    @RequestMapping("/getSomeBooks")
    @ResponseBody
    public Object getSomeBooks(Book book, @RequestParam(name = "page",defaultValue = "1") int page,@RequestParam(name = "limit",defaultValue = "5") int limit){
        System.out.println(book);
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Book> books = bookService.getSomeBooks(book);
        Page<Book> p = (Page<Book>) books;
        map.put("books",books);
        map.put("page",p.toPageInfo());
        return map;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(@RequestBody Book book,@RequestParam(name = "page",defaultValue = "1") int page,@RequestParam(name = "limit",defaultValue = "5") int limit){
        bookService.deleteBookById(book.getBookId());
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Book> books = bookService.getSomeBooks(book);
        Page<Book> p = (Page<Book>) books;
        map.put("books",books);
        map.put("page",p.toPageInfo());
        return map;
    }

    @RequestMapping("/addBook")
    @ResponseBody
    public Object addSomeBook(@RequestBody Book book,@RequestParam(name = "page",defaultValue = "1") int page,@RequestParam(name = "limit",defaultValue = "5") int limit){
        bookService.addBook(book);
        Map map = new HashMap();
        PageHelper.startPage(page,limit);
        List<Book> books = bookService.getAllBooks();
        Page<Book> p = (Page<Book>) books;
        map.put("books",books);
        map.put("page",p.toPageInfo());
        return map;
    }
}
